//
//  RBSearchVC.m
//  zhongzhenglu
//
//  Created by XL on 2022/7/11.
//

#import "RBSearchVC.h"
#import "RBDefine.h"
#import "UIView+RBAdd.h"
#import "UIScrollView+RBAdd.h"
#import "RBSearchTagView.h"
#import "RBThemeConfig.h"
#import <Masonry.h>
#import "RBNavigationBar.h"
#import "RBTextField.h"
#import "UIButton+RBAdd.h"
#import <UIColor+YYAdd.h>
#import <UINavigationController+FDFullscreenPopGesture.h>
#import "RBPersistence.h"
#import "NSString+RBAdd.h"
#import "RBAccountManager.h"
#import "RBSearchRankView.h"
#import "RBSearchResultVC.h"
#import <UIControl+YYAdd.h>
#import "RBSearchResponse.h" //搜索

@interface RBSearchVC ()<UITextFieldDelegate>

@property(nonatomic, strong)RBNavigationBar *navigationBar;
@property(nonatomic, strong)UIScrollView *scrollView;
@property(nonatomic, strong)RBTextField *searchF;
@property(nonatomic, strong)RBSearchRankView *rankView;

@property (nonatomic, strong) RBSearchResponse *response;

@end

@implementation RBSearchVC

#pragma mark - Lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self setup];
    
    [self getData];
}

#pragma mark - Private

- (void)setup
{
    self.fd_prefersNavigationBarHidden = YES;
    self.view.backgroundColor = UIColor.whiteColor;
    self.navigationBar.hidden = NO;
}

- (void)fillData
{
    [self.scrollView rbSetContentWidth:kRBMainScreenWidth];
    
    [self.scrollView addView:[self headerViewWithTitle:@"热门搜索" selector:nil] withHeight:CGFLOAT_MIN width:kRBMainScreenWidth top:Zoom(20) bottom:0 left:0 right:0 centerX:0];
    [self.scrollView addView:({
        RBSearchTagView *view = RBSearchTagView.new;
        view.data = self.response.data.keywords;
        MJWeakSelf;
        view.block = ^(NSString * _Nonnull title) {
            weakSelf.searchF.text = title;
            [weakSelf goSearchResultVCWith:title class_id:@""];
        };
        view;
    }) withHeight:CGFLOAT_MIN width:kRBMainScreenWidth top:Zoom(16) bottom:0 left:0 right:0 centerX:0];
    
    [self.scrollView addView:[self headerViewWithTitle:@"分类" selector:nil] withHeight:CGFLOAT_MIN width:kRBMainScreenWidth top:Zoom(36) bottom:0 left:0 right:0 centerX:0];
    [self.scrollView addView:({
        NSMutableArray *titleArray = [NSMutableArray array];
        for (RBSearchCategoryModel *model in self.response.data.category) {
            [titleArray addObject:model.cate_name];
        }
        RBSearchTagView *view = RBSearchTagView.new;
        view.data = titleArray;
        MJWeakSelf;
        view.block = ^(NSString * _Nonnull title) {
            RBSearchCategoryModel *chooseModel = RBSearchCategoryModel.new;
            for (RBSearchCategoryModel *model in self.response.data.category) {
                if ([model.cate_name isEqualToString:title]) {
                    chooseModel = model;
                }
            }
            weakSelf.searchF.text = title;
            [weakSelf goSearchResultVCWith:title class_id:chooseModel.id];
        };
        view;
    }) withHeight:CGFLOAT_MIN width:kRBMainScreenWidth top:Zoom(16) bottom:0 left:0 right:0 centerX:0];
    
    NSArray *history = [RBPersistence getShowSearchHistoryWithUserId:[RBAccountManager getUserId] type:0];
    if (history.count)
    {
        [self.scrollView addView:[self headerViewWithTitle:@"搜索历史" selector:@selector(clearSearchEvent)] withHeight:CGFLOAT_MIN width:kRBMainScreenWidth top:Zoom(36) bottom:0 left:0 right:0 centerX:0];
        [self.scrollView addView:({
            RBSearchTagView *view = RBSearchTagView.new;
            view.data = history;
            MJWeakSelf;
            view.block = ^(NSString * _Nonnull title) {
                weakSelf.searchF.text = title;
                [weakSelf goSearchResultVCWith:title class_id:@""];
            };
            view;
        }) withHeight:CGFLOAT_MIN width:kRBMainScreenWidth top:Zoom(16) bottom:0 left:0 right:0 centerX:0];
    }
    
    self.rankView.data = self.response.data;
    [self.scrollView addView:self.rankView withHeight:self.rankView.suggestHeight width:kRBMainScreenWidth top:Zoom(38) bottom:Zoom(38) left:0 right:0 centerX:0];
}

#pragma mark - Network

- (void)getData {
    LCWeakSelf;
    [self viewLoadDataWithParam:^(NSMutableDictionary *dicM) {
        
    } path:@"api/search_info" post:YES log:YES responseClass:RBSearchResponse.class desView:self.view showHud:YES showPlaceHolder:NO sucBlock:^(RBSearchResponse *data) {
        weakSelf.response = data;
        [weakSelf fillData];
    } failBlock:^(RBSearchResponse *data) {
        [weakSelf.view showTip:data.message completion:nil];
    } reloadBlock:^{
    }];
}

#pragma mark - Event

- (void)backBtnTapped
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)searchEvent
{
    [self.view endEditing:YES];
    [self goSearchResultVCWith:self.searchF.text class_id:@""];
}
//进入搜索结果页
- (void)goSearchResultVCWith:(NSString *)title class_id:(NSString *)class_id {
    if (title.rbLength) {
        [RBPersistence addShowSearchHistoryWithItem:title userId:[RBAccountManager getUserId] type:0];
        [self fillData];
    }
    RBSearchResultVC *vc = RBSearchResultVC.new;
    vc.keyword = title;
    vc.class_id = class_id;
    MJWeakSelf;
    vc.block = ^(NSString * _Nonnull keyword) {
        weakSelf.searchF.text = keyword;
        [weakSelf fillData];
    };
    [self.navigationController pushViewController:vc animated:NO];
}

- (void)clearSearchEvent
{
    __weak typeof(self) weakSelf = self;
    UIAlertController *vc = [UIAlertController alertControllerWithTitle:@"提示" message:@"是否清空搜索历史" preferredStyle:UIAlertControllerStyleAlert];
    [vc addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }]];
     [vc addAction:[UIAlertAction actionWithTitle:@"清空" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
        [RBPersistence clearShowSearchHistoryWithUserId:[RBAccountManager getUserId] type:0];
        [weakSelf fillData];
    }]];
    [self presentViewController:vc animated:YES completion:nil];
}

#pragma mark - Delegate

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [self searchEvent];
    return YES;
}

#pragma mark - Setter

#pragma mark - Getter

- (RBNavigationBar *)navigationBar
{
    if (!_navigationBar)
    {
        self.navigationBar = ({
            RBNavigationBar *bar = RBNavigationBar.new;
            bar.needGradientView = NO;
            [self.view addSubview:bar];
            [bar mas_makeConstraints:^(MASConstraintMaker *make) {
                make.left.right.top.mas_equalTo(0);
                make.height.mas_equalTo(kRBStatusBarHeight + kRBNavigationBarHeight);
            }];
            [bar.naviBar addBackBtnWithWidth:50 image:[UIImage imageNamed:@"backBlack"]];
            [[bar.naviBar getBackBtn] removeAllTargets];
            [[bar.naviBar getBackBtn] rbAddTarget:self action:@selector(backBtnTapped)];
            
            UIButton *searchBtn = UIButton.new;
            [searchBtn rbSetTitle:@"搜索"];
            [searchBtn rbSetFontSize:18];
            [searchBtn rbSetTitleColor:[UIColor colorWithHexString:@"#222222"]];
            [searchBtn rbAddTarget:self action:@selector(searchEvent)];
            [bar.naviBar addSubview:searchBtn];
            [searchBtn mas_makeConstraints:^(MASConstraintMaker *make) {
                make.top.bottom.right.mas_equalTo(0);
                make.width.mas_equalTo(56);
            }];
            
            UIView *searchView = UIView.new;
            [bar.naviBar addSubview:searchView];
            [searchView mas_makeConstraints:^(MASConstraintMaker *make) {
                make.left.mas_equalTo(bar.naviBar.getBackBtn.mas_right);
                make.right.mas_equalTo(searchBtn.mas_left);
                make.height.mas_equalTo(36);
                make.centerY.mas_equalTo(0);
            }];
            searchView.backgroundColor = [UIColor colorWithHexString:@"#F9F9F9"];
            [searchView rbSetCornerRadius:18];
            
            
            UIImageView *imgView = UIImageView.new;
            imgView.image = [UIImage imageNamed:@"homeSearchIcon"];
            [searchView addSubview:imgView];
            [imgView mas_makeConstraints:^(MASConstraintMaker *make) {
                make.left.mas_equalTo(14);
                make.centerY.mas_equalTo(0);
                make.width.height.mas_equalTo(16);
            }];
            
            RBTextField *textF = RBTextField.new;
            self.searchF = textF;
            textF.delegate = self;
            [searchView addSubview:textF];
            [textF mas_makeConstraints:^(MASConstraintMaker *make) {
                make.top.bottom.mas_equalTo(0);
                make.left.mas_equalTo(imgView.mas_right).offset(8);
                make.right.mas_equalTo(-20);
            }];
            textF.placeholder = @"请输入商品名称";
            textF.font = [UIFont systemFontOfSize:12];
            textF.textColor = [RBThemeConfig textBlackColor];
            textF.keyboardType = UIKeyboardTypeWebSearch;
            
            bar;
        });
    }
    return _navigationBar;
}

- (UIScrollView *)scrollView
{
    if (!_scrollView)
    {
        self.scrollView = ({
            UIScrollView *view = UIScrollView.new;
            view.showsVerticalScrollIndicator = NO;
            [self.view addSubview:view];
            [view mas_makeConstraints:^(MASConstraintMaker *make) {
                make.left.right.mas_equalTo(0);
                make.bottom.mas_equalTo(0);
                make.top.mas_equalTo(self.navigationBar.mas_bottom);
            }];
            view;
        });
    }
    return _scrollView;
}

- (UIView *)headerViewWithTitle: (NSString *)title selector: (SEL)selector
{
    UIView *view = UIView.new;
    
    UILabel *titleL = UILabel.new;
    titleL.text = title;
    titleL.font = [UIFont systemFontOfSize:15];
    titleL.textColor = [RBThemeConfig textBlackColor];
    [view addSubview:titleL];
    [titleL mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(Zoom(11));
        make.top.bottom.mas_equalTo(0);
        
    }];
    
    if (selector)
    {
        UIImageView *imgView = [UIImageView.alloc initWithImage:[UIImage imageNamed:@"searchHistoryDelete"]];
        [view addSubview:imgView];
        [imgView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.width.height.mas_equalTo(Zoom(12));
            make.centerY.mas_equalTo(0);
            make.right.mas_equalTo(-Zoom(11));
        }];
        [imgView setResponseArea:UIEdgeInsetsMake(Zoom(11), Zoom(11), Zoom(11), Zoom(11))];
        [imgView rbAddTapGesWithTarget:self action:selector];
    }
    
    return view;
}

- (RBSearchRankView *)rankView
{
    if (!_rankView)
    {
        self.rankView = ({
            RBSearchRankView *view = RBSearchRankView.new;
            view;
        });
    }
    return _rankView;
}

@end
